import 'package:bxultimate/app/theme/app_theme.dart';
import 'package:bxultimate/app/theme/gaps.dart';
import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

class AppCalendar extends StatefulWidget {
  final List<num> checkDate;
  DateTime? manuallySelectedDate;
  Function(DateTime)? onDateSelected;

  AppCalendar({super.key, required this.checkDate, this.manuallySelectedDate,this.onDateSelected});

  @override
  State<AppCalendar> createState() => _AppCalendarState();
}

class _AppCalendarState extends State<AppCalendar> {
  DateTime selectedDate = DateTime.now();

  //被手动选中的日期
  //赋值默认选择当天，不赋值则不选择

  //头部显示的星期
  final weekdays = [
    '周日',
    '周一',
    '周二',
    '周三',
    '周四',
    '周五',
    '周六',
  ];

  //每个月对应的天数
  late int daysInMonth;

  late DateTime firstDay;

  //将周日调整为第一天
  late int startingWeekday;

  //是否当天
  bool isToday = true;

  //是否被选中
  bool isSelected = false;

  @override
  Widget build(BuildContext context) {
    //该处数据每次遍历都需要用到，不能放到init里
    daysInMonth = DateTime(selectedDate.year, selectedDate.month + 1, 0).day;
    firstDay = DateTime(selectedDate.year, selectedDate.month, 1);
    startingWeekday = (firstDay.weekday - 7) % 7;

    return Column(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.symmetric(
              horizontal: 16.0, vertical: AppTheme.iDefaultPadding),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text(
                '${selectedDate.year.toString().padLeft(2, '0')}-'
                '${selectedDate.month.toString().padLeft(2, '0')}-'
                '${selectedDate.day.toString().padLeft(2, '0')}',
                style: const TextStyle(fontSize: 20),
              ),

              TDButton(
                text: '回到今天',
                theme: TDButtonTheme.primary,
                size: TDButtonSize.extraSmall,
                type: TDButtonType.outline,
                onTap: () {
                  setState(() {
                    widget.manuallySelectedDate = null;
                    selectedDate = DateTime.now();
                    widget.onDateSelected!(selectedDate);
                  });
                },
              )

              // IconButton(
              //   icon: const Icon(Icons.arrow_forward),
              //   onPressed: () {
              //     setState(() {
              //       manuallySelectedDate = null;
              //       selectedDate = DateTime(selectedDate.year, selectedDate.month + 1, selectedDate.day);
              //     });
              //   },
              // ),
            ],
          ),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: weekdays.map((day) {
            return Text(day,
                style: const TextStyle(fontSize: 14, color: Colors.grey));
          }).toList(),
        ),
        calendarGrid(),
      ],
    );
  }

  calendarGrid() {
    return CustomScrollView(
      shrinkWrap: true, //收缩
      slivers: <Widget>[
        SliverGrid(
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 7),
          delegate: SliverChildBuilderDelegate(
            (BuildContext context, int index) {
              if (index < startingWeekday) return Container();

              int day = index - startingWeekday + 1;
              DateTime currentDate =
                  DateTime(selectedDate.year, selectedDate.month, day);

              isToday = currentDate.day == DateTime.now().day &&
                  currentDate.month == DateTime.now().month &&
                  currentDate.year == DateTime.now().year;

              isSelected = currentDate.year == selectedDate.year &&
                  currentDate.month == selectedDate.month &&
                  currentDate.day == selectedDate.day;

              return GestureDetector(
                onTap: () {
                  // 处理日期点击事件
                  setState(() {
                    // 更新被选中的日期
                    selectedDate = currentDate;
                    widget.manuallySelectedDate = currentDate;
                    print("选择的日期:${widget.manuallySelectedDate}");
                    if(widget.onDateSelected !=null){
                      widget.onDateSelected!(currentDate);
                    }
                  });
                },
                child: UnconstrainedBox(
                  child: Container(
                    width: 50,
                    height: 50,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(
                          color: isToday
                              ? AppTheme.primaryColor
                              : Colors.transparent),
                      color: isSelected
                          ? AppTheme.primaryColor
                          : Colors.transparent,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          day.toString(),
                          style: TextStyle(
                            color: isSelected
                                ? Colors.white
                                : (isToday ? Colors.red : Colors.black),
                            fontWeight: isSelected
                                ? FontWeight.bold
                                : FontWeight.normal,
                          ),
                        ),
                        widget.checkDate.contains(day)
                            ? Icon(
                                Icons.check,
                                size: 12,
                                color: Colors.blue,
                              )
                            : SizedBox(),
                      ],
                    ),
                  ),
                ),
              );
            },
            childCount: daysInMonth + startingWeekday,
          ),
        ),
      ],
    );
  }
}
